package com.spic.business.vehicle.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spic.business.common.core.utils.DateUtil;
import com.spic.business.common.core.utils.ValidatorUtil;
import com.spic.business.hik.constant.HkConstant;
import com.spic.business.hik.utils.HkResultUtlis;
import com.spic.business.vehicle.domain.VehicleManagement;
import com.spic.business.vehicle.domain.VehicleManagementDirty;
import com.spic.business.vehicle.mapper.VehicleManagementDirtyMapper;
import com.spic.business.vehicle.mapper.VehicleManagementMapper;
import com.spic.business.vehicle.service.IVehicleManagementService;
import com.spic.common.core.exception.ServiceException;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.utils.bean.BeanUtils;
import com.spic.common.security.utils.DictUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.groups.Default;
import java.util.Date;
import java.util.List;

/**
 * 车辆管理Service业务层处理
 *
 * @author spic
 * @date 2022-07-17
 */
@Service
@Slf4j
public class VehicleManagementServiceImpl implements IVehicleManagementService {

    @Autowired
    private VehicleManagementMapper vehicleManagementMapper;
    @Autowired
    private VehicleManagementDirtyMapper vehicleManagementDirtyMapper;

    /**
     * 查询车辆管理
     *
     * @param clientid 车辆管理主键
     * @return 车辆管理
     */
    @Override
    public VehicleManagement selectVehicleManagementByClientid(Long clientid) {
        return vehicleManagementMapper.selectVehicleManagementByClientid(clientid);
    }

    /**
     * 查询车辆管理列表
     *
     * @param vehicleManagement 车辆管理
     * @return 车辆管理
     */
    @Override
    public List<VehicleManagement> selectVehicleManagementList(VehicleManagement vehicleManagement) {
        vehicleManagement.setState("0");
        return vehicleManagementMapper.selectVehicleManagementList(vehicleManagement);
    }

    /**
     * 新增车辆管理
     *
     * @param vehicleManagement 车辆管理
     * @return 结果
     */
    @Override
    public int insertVehicleManagement(VehicleManagement vehicleManagement) {
        VehicleManagement param = new VehicleManagement();
        String plateno = vehicleManagement.getPlateno();
        param.setPlateno(plateno);
        param.setState("0");
        List<VehicleManagement> list = selectVehicleManagementList(param);
        if (list.size() > 0) {
            throw new ServiceException("车辆已存在!");
        }
        //车辆充值
        vehicleManagementMapper.insertVehicleManagement(vehicleManagement);
        String startTimeStr = DateUtil.fmtDateToYMD(vehicleManagement.getStartTime());
        String endTimeStr = DateUtil.fmtDateToYMD(vehicleManagement.getEndTime());
        String parkIndexCode = vehicleManagement.getParkIndexCode();
        String[] parkCodes = parkIndexCode.split(",");
        for (int i = 0; i < parkCodes.length; i++) {
            JSONObject object = new JSONObject();
            object.put("parkSyscode", parkCodes[i]);
            object.put("plateNo", plateno);
            object.put("startTime", startTimeStr);
            object.put("endTime", endTimeStr);
            String response = HkResultUtlis.doPostStringArtemis(HkConstant.HK_CAR_CHARGE, object.toJSONString());
            log.info("充值接口:车牌号{}, 返回内容{}", plateno ,response);
        }
        return 1;
    }

    /**
     * 修改车辆管理
     *
     * @param vehicleManagement 车辆管理
     * @return 结果
     */
    @Override
    public int updateVehicleManagement(VehicleManagement vehicleManagement) {
        vehicleManagement.setUpdateTime(DateUtils.getNowDate());
        return vehicleManagementMapper.updateVehicleManagement(vehicleManagement);
    }

    /**
     * 批量删除车辆管理
     *
     * @param clientids 需要删除的车辆管理主键
     * @return 结果
     */
    @Override
    public int deleteVehicleManagementByClientids(Long[] clientids) {
        int i = vehicleManagementMapper.updateByIds(clientids);
        return i;
        //return vehicleManagementMapper.deleteVehicleManagementByClientids(clientids);
    }

    /**
     * 删除车辆管理信息
     *
     * @param clientid 车辆管理主键
     * @return 结果
     */
    @Override
    public int deleteVehicleManagementByClientid(Long clientid) {
        return vehicleManagementMapper.deleteVehicleManagementByClientid(clientid);
    }

    @Override
    public String importData(List<VehicleManagement> list) {
        if (list == null || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        //字典label转成value
        list.stream().forEach(item -> {
            item.setPlatetype(DictUtils.getDictValueByTypeAndLabel(item.getPlatetype(), "sys_hik_plateType", "0"));
            item.setPlatecolor(DictUtils.getDictValueByTypeAndLabel(item.getPlatecolor(), "sys_hik_plateColor", "0"));
            item.setVehicletype(DictUtils.getDictValueByTypeAndLabel(item.getVehicletype(), "sys_hik_vehicleType", "1"));
            item.setVehiclecolor(DictUtils.getDictValueByTypeAndLabel(item.getVehiclecolor(), "sys_hik_vehicleColor", "0"));
        });
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (VehicleManagement vehicle : list) {
            try {
                insertVehicleManagement(vehicle);
                successNum++;
            } catch (Exception e) {
                failureMsg.append(e.getMessage());
                failureNum++;
            }
        }
        successMsg.insert(0, "数据已导入成功！共新增 " + successNum + " 条,导入失败" + failureNum + "条, 数据如下：");
        return successMsg.toString() + failureMsg;
    }

    @Override
    public int alarmCar(VehicleManagement vehicle) {
        JSONObject json = new JSONObject();
        json.put("plateNo", vehicle.getPlateno());
        String result = HkResultUtlis.doPostStringArtemis(HkConstant.HK_ALARMCAR_ADDITION, json.toString());
        JSONObject resultJson = JSONObject.parseObject(result);
        if ("0".equals(resultJson.getString("code"))) {
            String alarmSyscode = resultJson.getJSONObject("data").getString("alarmSyscode");
            vehicle.setAlarmsyscode(alarmSyscode);
            vehicle.setAlarmcar("Y");
            vehicleManagementMapper.updateVehicleManagement(vehicle);
        }
        return 1;
    }

    @Override
    public int delAlarmCar(Long[] clientids) {
        JSONObject json = new JSONObject();
        for (int i = 0; i < clientids.length; i++) {
            VehicleManagement vehicle = vehicleManagementMapper.selectVehicleManagementByClientid(clientids[i]);
            if (StringUtils.isNotEmpty(vehicle.getAlarmsyscode())) {
                json.put("alarmSyscodes", vehicle.getAlarmsyscode());
                String result = HkResultUtlis.doPostStringArtemis(HkConstant.HK_ALARMCAR_DELETION, json.toString());
                JSONObject resultJson = JSONObject.parseObject(result);
                if ("0".equals(resultJson.getString("code"))) {
                    vehicle.setAlarmcar("N");
                    vehicleManagementMapper.updateVehicleManagement(vehicle);
                }
            }
        }
        return 1;
    }

    @Override
    public String carsCharge(VehicleManagement vehicleManagement) {
        String[] clientIds = vehicleManagement.getClientIds().split(",");
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (int i = 0; i < clientIds.length; i++) {
            String clientId = clientIds[i];
            try {
                VehicleManagement management = selectVehicleManagementByClientid(Long.valueOf(clientId));
                carCharge(management.getClientid(), management.getPlateno(), vehicleManagement.getParkIndexCode(), vehicleManagement.getStartTime(), vehicleManagement.getEndTime());
                successNum++;
            } catch (Exception e) {
                failureMsg.append(e.getMessage());
                failureNum++;
            }
        }
        successMsg.insert(0, "充值成功 " + successNum + " 辆，充值失败" + failureNum + "辆");
        return successMsg.toString();
    }

    public void carCharge(Long clientId, String plateNo, String parkSyscode, Date startTime, Date endTime) {
        String startTimeStr = DateUtil.fmtDateToYMD(startTime);
        String endTimeStr = DateUtil.fmtDateToYMD(endTime);
        String[] parkCodes = parkSyscode.split(",");
        String parkCode = null;
        for (int i = 0; i < parkCodes.length; i++) {
            JSONObject object = new JSONObject();
            object.put("parkSyscode", parkCodes[i]);
            object.put("plateNo", plateNo);
            object.put("startTime", startTimeStr);
            object.put("endTime", endTimeStr);
            String response = HkResultUtlis.doPostStringArtemis(HkConstant.HK_CAR_CHARGE, object.toJSONString());
            JSONObject resultJson = JSONObject.parseObject(response);
            if ("0".equals(resultJson.getString("code"))) {
                if(parkCode == null) {
                    parkCode = parkCodes[i];
                } else {
                    parkCode = parkCode + "," + parkCodes[i];
                }
                VehicleManagement vehicle = new VehicleManagement();
                vehicle.setClientid(clientId);
                vehicle.setStartTime(startTime);
                vehicle.setEndTime(endTime);
                vehicle.setParkIndexCode(parkCode);
                updateVehicleManagement(vehicle);
            } else {
                throw new ServiceException(plateNo + "充值失败，失败原因：" + resultJson.getString("msg")) ;
            }
        }
    }


    @Override
    public void filterDirtyData() {
        vehicleManagementDirtyMapper.deleteAll();
        List<VehicleManagement> vehicleManagements = vehicleManagementMapper.selectVehicleManagementList(new VehicleManagement());
        for(VehicleManagement vehicleManagement : vehicleManagements) {
            List<String> list = ValidatorUtil.validate(vehicleManagement, Default.class);
            if(list != null && list.size() > 0) {
                String dirtyReason = String.join(",", list);
                VehicleManagementDirty dirty = new VehicleManagementDirty();
                dirty.setIncomplete(1);
                dirty.setDirtyReason(dirtyReason);
                BeanUtils.copyBeanProp(dirty, vehicleManagement);
                vehicleManagementDirtyMapper.insertVehicleManagementDirty(dirty);
            }
        }
    }

}
